#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/26 22:21
# @Author  : FLC
# @Contact : beifeng107@foxmail.com
# @File    : tags.py.py
# @Software: PyCharm
from interface.api_object.apis.we_work import WeWork
from interface.api_object.utils.file_tool import FileTool
from interface.api_object.utils.log_tool import logger


class Tags(WeWork):

    def __init__(self):
        logger.info("初始化标签管理API对象")
        yaml_data = FileTool.read_yaml("corp_info")
        corp_id = yaml_data.get("corpid").get("mycorp")
        corp_secret = yaml_data.get("corpsecret").get("department")
        self.token = self.get_access_token(corp_id, corp_secret)

    def create(self, data):
        logger.info("创建标签")
        url = "/tag/create"
        method = "POST"
        param = {
            "access_token": self.token
        }
        return self.send(method, url, params=param, json=data)

    def search(self):
        logger.info("获取所有标签信息")
        url = "/tag/list"
        method = "GET"
        param = {
            "access_token": self.token
        }
        return self.send(method, url, params=param)

    def delete(self, tag_id):
        logger.info(f"删除标签， 标签id是：{tag_id}")
        url = "/tag/delete"
        method = "GET"
        param = {
            "access_token": self.token,
            "tagid": tag_id
        }
        return self.send(method, url, params=param)

    def update(self, data):
        url = "/tag/update"
        method = "POST"
        param = {
            "access_token": self.token
        }

        return self.send(method, url, params=param, json=data)

    def is_in_tags_list(self, tag_id):
        logger.info("检测标签是否存在")
        r = self.search().json()
        logger.info(f"标签信息为：{r}")
        all_ids = self.json_parser(r, "$..tagid")
        if all_ids:
            if tag_id in all_ids:
                return True
        return False

    def get_tag_name(self, tag_id):
        logger.info("获取便签名字")
        r = self.search().json()
        logger.info(f"标签信息为：{r}")
        tag = self.json_parser(r, f"$..taglist[?(@.tagid=={tag_id})]")
        if tag:
            return tag[0].get("tagname")
        else:
            return None